package com.sunshine.pay.controller;

import com.sunshine.pay.dao.MerchantBalancesDao;
import com.sunshine.pay.dao.UserBalancesDao;
import com.sunshine.pay.entity.MerchantBalances;
import com.sunshine.pay.entity.UserBalances;
import com.sunshine.pay.entity.Order;
import com.sunshine.pay.entity.OrderItem;
import com.sunshine.pay.service.OrderService;
import com.sunshine.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import sunshine.commcon.util.entity.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/orders")
public class OrderController {
    
    @Resource
    private OrderService orderService;
    @Resource
    private MerchantBalancesDao merchantBalancesDao;
    @Resource
    private UserBalancesDao userBalancesDao;
    
    /**
     * 创建订单
     * @param request HTTP请求
     * @param orderRequest 订单请求数据
     * @return 订单信息
     */
    @PostMapping("/create")
    public Result<Order> createOrder(HttpServletRequest request, @RequestBody OrderRequest orderRequest) {
        // 从token中提取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        if (userId == null) {
            return Result.fail("用户未登录或token无效");
        }
        
        log.info("用户创建订单: 用户ID={}, 订单项数量={}", userId, orderRequest.getOrderItems().size());
        
        return orderService.createOrder(userId, orderRequest.getOrderItems());
    }
    
    /**
     * 获取订单详情
     * @param request HTTP请求
     * @param orderId 订单ID
     * @return 订单信息
     */
    @GetMapping("/detail/{orderId}")
    public Result<Order> getOrderDetail(HttpServletRequest request, @PathVariable Long orderId) {
        // 从token中提取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        if (userId == null) {
            return Result.fail("用户未登录或token无效");
        }
        
        log.info("用户获取订单详情: 用户ID={}, 订单ID={}", userId, orderId);
        
        Result<Order> result = orderService.getOrderById(orderId);
        // 检查订单是否属于该用户
        if (result.getCode() == 200 && !result.getData().getUserId().equals(userId)) {
            return Result.fail("无权限查看该订单");
        }
        
        return result;
    }
    
    /**
     * 获取用户订单列表
     * @param request HTTP请求
     * @return 订单列表
     */
    @GetMapping("/list")
    public Result<List<Order>> getOrderList(HttpServletRequest request) {
        // 从token中提取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        if (userId == null) {
            return Result.fail("用户未登录或token无效");
        }
        
        log.info("用户获取订单列表: 用户ID={}", userId);
        
        return orderService.getOrdersByUserId(userId);
    }
    
    /**
     * 更新订单状态
     * @param request HTTP请求
     * @param orderId 订单ID
     * @param statusRequest 状态请求
     * @return 操作结果
     */
    @PostMapping("/updateStatus/{orderId}")
    public Result<Boolean> updateOrderStatus(HttpServletRequest request, @PathVariable Long orderId, @RequestBody StatusRequest statusRequest) {
        // 从token中提取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        if (userId == null) {
            return Result.fail("用户未登录或token无效");
        }
        
        log.info("用户更新订单状态: 用户ID={}, 订单ID={}, 状态={}", userId, orderId, statusRequest.getStatus());
        
        return orderService.updateOrderStatus(orderId, statusRequest.getStatus());
    }
    
    /**
     * 用户确认收货
     * @param request HTTP请求
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PostMapping("/confirm/{orderId}")
    public Result<Boolean> confirmReceipt(HttpServletRequest request, @PathVariable Long orderId) {
        // 从token中提取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        if (userId == null) {
            return Result.fail("用户未登录或token无效");
        }
        
        log.info("用户确认收货: 用户ID={}, 订单ID={}", userId, orderId);
        
        return orderService.confirmReceipt(orderId, userId);
    }
    
    /**
     * 获取商家订单列表
     * @param request HTTP请求
     * @return 订单列表
     */
    @GetMapping("/merchant/list")
    public Result<List<Order>> getMerchantOrderList(HttpServletRequest request) {
        // 从token中提取商家ID
        Long merchantId = TokenUtil.getUserIdFromRequest(request);
        if (merchantId == null) {
            return Result.fail("商家未登录或token无效");
        }
        
        log.info("商家获取订单列表: 商家ID={}", merchantId);
        
        return orderService.getOrdersByMerchantId(merchantId);
    }
    
    /**
     * 商家发货
     * @param request HTTP请求
     * @param orderId 订单ID
     * @return 操作结果
     */
    @PostMapping("/ship/{orderId}")
    public Result<Boolean> merchantShipOrder(HttpServletRequest request, @PathVariable Long orderId) {
        // 从token中提取商家ID
        Long merchantId = TokenUtil.getUserIdFromRequest(request);
        if (merchantId == null) {
            return Result.fail("商家未登录或token无效");
        }
        
        log.info("商家发货: 商家ID={}, 订单ID={}", merchantId, orderId);
        
        return orderService.merchantShipOrder(orderId, merchantId);
    }
    
    /**
     * 获取商家余额
     * @param request HTTP请求
     * @return 商家余额信息
     */
    @GetMapping("/merchant/balance")
    public Result<MerchantBalances> getMerchantBalance(HttpServletRequest request) {
        // 从token中提取商家ID
        Long merchantId = TokenUtil.getUserIdFromRequest(request);
        if (merchantId == null) {
            return Result.fail("商家未登录或token无效");
        }

        log.info("商家获取余额信息: 商家ID={}", merchantId);

        try {
            MerchantBalances merchantBalances = merchantBalancesDao.queryByMerchantId(merchantId);
            if (merchantBalances == null) {
                // 如果商家余额账户不存在，则创建一个
                log.info("商家余额账户不存在，创建新账户: 商家ID={}", merchantId);
                merchantBalances = new MerchantBalances();
                merchantBalances.setMerchantId(merchantId);
                merchantBalances.setBalance(0.0);
                merchantBalances.setUpdatedAt(new Date());
                merchantBalancesDao.insert(merchantBalances);
            }

            return Result.ok(merchantBalances);
        } catch (Exception e) {
            log.error("获取商家余额时发生异常: 商家ID={}", merchantId, e);
            return Result.fail("系统异常，获取余额信息失败");
        }
    }
    
    /**
     * 获取用户余额
     * @param request HTTP请求
     * @return 用户余额信息
     */
    @GetMapping("/user/balance")
    public Result<UserBalances> getUserBalance(HttpServletRequest request) {
        // 从token中提取用户ID
        Long userId = TokenUtil.getUserIdFromRequest(request);
        if (userId == null) {
            return Result.fail("用户未登录或token无效");
        }

        log.info("用户获取余额信息: 用户ID={}", userId);

        try {
            UserBalances userBalances = userBalancesDao.queryByUserId(userId);
            if (userBalances == null) {
                // 如果用户余额账户不存在，则创建一个
                log.info("用户余额账户不存在，创建新账户: 用户ID={}", userId);
                userBalances = new UserBalances();
                userBalances.setUserId(userId);
                userBalances.setBalance(0.0);
                userBalances.setUpdatedAt(new Date());
                userBalancesDao.insert(userBalances);
            }

            return Result.ok(userBalances);
        } catch (Exception e) {
            log.error("获取用户余额时发生异常: 用户ID={}", userId, e);
            return Result.fail("系统异常，获取余额信息失败");
        }
    }
    
    /**
     * 订单请求数据载体
     */
    public static class OrderRequest {
        private List<OrderItem> orderItems;
        
        public List<OrderItem> getOrderItems() {
            return orderItems;
        }
        
        public void setOrderItems(List<OrderItem> orderItems) {
            this.orderItems = orderItems;
        }
    }
    
    /**
     * 状态请求数据载体
     */
    public static class StatusRequest {
        private Integer status;
        
        public Integer getStatus() {
            return status;
        }
        
        public void setStatus(Integer status) {
            this.status = status;
        }
    }
}